//
//  PhotoSelectorViewController.swift
//  图片选择器
//
//  Created by 林柱强 on 16/2/28.
//  Copyright © 2016年 林柱强. All rights reserved.
//

import UIKit

private let PhotoSelectorViewReuseIdentifier = "PhotoSelectorViewReuseIdentifier"

class PhotoSelectorViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    private func setupUI() {
        
        //添加子控件
        view.addSubview(collectionView)
        
        //布局子控件
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        var cons = [NSLayoutConstraint]()
        
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["collectionView": collectionView])
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["collectionView": collectionView])
        
        view.addConstraints(cons)
    }
    
    //MARK: - 懒加载
    private lazy var collectionView: UICollectionView = {
        let clv = UICollectionView(frame: CGRectZero, collectionViewLayout: PhotoSelectorViewLayout())
        clv.dataSource = self
        clv.registerClass(PhotoSelectorCell.self, forCellWithReuseIdentifier: PhotoSelectorViewReuseIdentifier)
        return clv
    }()
    
    lazy var pictureImages = [UIImage]()
}

extension PhotoSelectorViewController: UICollectionViewDataSource, PhotoSelectorCellDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureImages.count + 1
//        return 10
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PhotoSelectorViewReuseIdentifier, forIndexPath: indexPath) as! PhotoSelectorCell
        cell.PhotoCellDelegate = self
        cell.backgroundColor = UIColor.blueColor()
        cell.image = (pictureImages.count == indexPath.item) ? nil : pictureImages[indexPath.item]
        
        
        return cell
    }
    
    func photoDidAddSelector(cell: PhotoSelectorCell) {
        
        /*
        case PhotoLibrary     照片库 所有同步的照片，不能删除
        case Camera           相册   拍摄的照片，可以删除
        case SavedPhotosAlbum 相机
        */
        //1. 判断能不能打开照片库
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary){
            return
        }
        //创建照片选择器
        let vc = UIImagePickerController()
        vc.delegate = self
        //设置允许用户编辑进入编辑界面
//        vc.allowsEditing = true
        presentViewController(vc, animated: true, completion: nil)
    }
    
    func photoDidRemoveSelector(cell: PhotoSelectorCell) {
        //1. 从数组中移除当前点击的图片
        let indexPath = collectionView.indexPathForCell(cell)
        pictureImages.removeAtIndex(indexPath!.item)
        //2.刷新表格
        collectionView.reloadData()
    }
    /**
     选中相片之后调用
     
     - parameter picker:      促发事件的控制器
     - parameter image:       当前选中的照片
     - parameter editingInfo: 编辑之后的图片
     */
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        /**
        *   注意: 一般情况下，只要涉及到从相册中获取图片的功能，
                 都需要内存处理
        *   一般情况下一个程序应用要占用20M内存，当内存飙升到500M左右的时候系统就会发送内存警告，此时就需要释放内存，否则就会闪退
        *   只要内存释放到100M左右，应用程序就不会闪退
        *   也就是说一个应用程序占用内存20~100时，是比较安全的内容范围
        *
        */
        
        let newImage = image.imageWithScale(300)
        
        
        //1.将当前选中的图片添加到数组中
        pictureImages.append(newImage)
        collectionView.reloadData()
        
        
        //注意: 如果实现了该方法，需要我们自己关闭图片选择器
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}
@objc
protocol PhotoSelectorCellDelegate: NSObjectProtocol {
    
    optional func photoDidAddSelector(cell: PhotoSelectorCell)
    
    optional func photoDidRemoveSelector(cell: PhotoSelectorCell)
}


class PhotoSelectorCell: UICollectionViewCell {
    
    var image: UIImage? {
        didSet{
            if image != nil {
                removeButton.hidden = false
                addButton.setBackgroundImage(image!, forState: .Normal)
                addButton.userInteractionEnabled = false
            }else {
                removeButton.hidden = true
                addButton.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: .Normal)
                addButton.userInteractionEnabled = true
            }
        }
    }
    
    weak var PhotoCellDelegate: PhotoSelectorCellDelegate?
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        setupUI()
    }

    private func setupUI() {
        //添加子控件
        contentView.addSubview(addButton)
        contentView.addSubview(removeButton)
        
        //布局子控件
        addButton.translatesAutoresizingMaskIntoConstraints = false
        removeButton.translatesAutoresizingMaskIntoConstraints = false
        var cons = [NSLayoutConstraint]()
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[addButton]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["addButton": addButton])
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[addButton]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["addButton": addButton])
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:[removeButton]-2-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["removeButton": removeButton])
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-2-[removeButton]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["removeButton": removeButton])
        
        contentView.addConstraints(cons)
    }
    
    func removeBtnClick() {
        
        PhotoCellDelegate?.photoDidRemoveSelector!(self)
    }
    
    func addBtnClick() {
        
        PhotoCellDelegate?.photoDidAddSelector!(self)
    }
    
    //MARK - 懒加载
    private lazy var removeButton: UIButton = {
        let btn = UIButton()
        btn.hidden = true
        btn.setBackgroundImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        btn.addTarget(self, action: "removeBtnClick", forControlEvents: .TouchUpInside)
        
        return btn
    }()
    
    private lazy var addButton: UIButton = {
        let btn = UIButton()
        btn.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
        btn.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "compose_pic_add_highlighted"), forState: .Highlighted)
        btn.addTarget(self, action: "addBtnClick", forControlEvents: .TouchUpInside)
        
        return btn
    }()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


class PhotoSelectorViewLayout: UICollectionViewFlowLayout {
    override func prepareLayout() {
        super.prepareLayout()
        
        itemSize = CGSize(width: 80, height: 80)
        
        minimumInteritemSpacing = 10
        minimumLineSpacing = 10
        sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        
    }
}
